import sys
import os
import subprocess
import winreg

from pathlib import Path

import Utils

class OpencvConfiguration:
    opencvVersion = "4.10.0"   
    opencvDirectory = "./Rasterizer/vendor/opencv"
    opencvBuildDirectory =  "./Rasterizer/vendor/opencv/opencv/build/x64/vc16/bin"
    paths_to_add = []

    @classmethod
    def Validate(cls):
        if (not cls.CheckOpenCV()):
            print("Opencv is not installed.")
            return False
       
        return True

    @classmethod
    def CheckOpenCV(cls):
      
        opencvPath = os.path.abspath(cls.opencvBuildDirectory)
        cls.paths_to_add.append(opencvPath)
        # Check if OpenCV path is already in the system PATH

        paths = os.environ.get('PATH', '').split(os.pathsep)

        if opencvPath in paths:
            print(f'{opencvPath} 已经在系统的 PATH 环境变量中。')
            print(f"Correct Opencv located at {os.path.abspath(cls.opencvDirectory)}")
            return True

         # Add OpenCV path to system PATH using setx /M (for machine-wide)
        else:
             
            try:
                cls.__InstallOpencv()
                return True
            except subprocess.CalledProcessError as e:
                print(f'添加 {opencvPath} 到系统 PATH 环境变量失败: {e}')
                return False
    @classmethod
    def __InstallOpencv(cls):
        permissionGranted = False
        while not permissionGranted:
            reply = str(input("请安装OpenCV {0:s}? [Y/N]: ".format(cls.opencvVersion))).lower().strip()[:1]
            if reply == 'n':
                return
            permissionGranted = (reply == 'y')
        
        opencvInstallURL = f"https://github.com/opencv/opencv/releases/download/{cls.opencvVersion}/opencv-{cls.opencvVersion}-windows.exe"
        opencvPath = f"{cls.opencvDirectory}/opencv-{cls.opencvVersion}-windows.exe"
        print("Downloading {0:s} to {1:s}".format(opencvInstallURL, opencvPath))
        Utils.DownloadFile(opencvInstallURL, opencvPath)
        print("Running opencv installer...")
        os.startfile(os.path.abspath(opencvPath))
        cls.add_to_path(cls.paths_to_add)
        

    @classmethod
    def add_to_path(cls,new_paths):
        # 获取当前 PATH 变量的值
        key_path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
        reg_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path, 0, winreg.KEY_ALL_ACCESS)
        current_path, _ = winreg.QueryValueEx(reg_key, 'Path')
       
        # 将新的路径添加到当前 PATH 变量中
        new_path_list = new_paths + current_path.split(';')
        new_path_set = set(new_path_list)
        new_path_sorted = sorted(new_path_set)
        new_path = ';'.join(new_path_sorted)

        # 设置新的 PATH 变量值到注册表
        winreg.SetValueEx(reg_key, 'Path', 0, winreg.REG_EXPAND_SZ, new_path)

        # 关闭注册表键
        winreg.CloseKey(reg_key)
        print('已成功更新系统的 PATH 环境变量。')


    
if __name__ == "__main__":
    OpencvConfiguration.Validate()